class SessionsController < ApplicationController

  def create
    if self.current_user = User.authenticate(params[:email],params[:password])
      successful_login
    else
      failed_login "Invalid login or password, try again please."[:invalid_login_message]
    end
  end

  def destroy
    cookies.delete :login_token
    reset_session
    flash[:notice] = "You have been logged out."
    redirect_back_or_default('/')
  end

  private

  def successful_login
    cookies[:login_token]= {:value =>
      "#{current_user.id};#{current_user.reset_login_key!}", :expires => 1.year.from_now.utc} if params[:remember_me] == "1"
    redirect_back_or_default('/')
    flash[:notice] = "Logged in successfully"
  end

  def failed_login(message)
    flash.now[:error] = message
    render :action => 'new'
  end
end
